package com.supersit.GZFDA.activity;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.supersit.GZFDA.R;
import com.supersit.GZFDA.api.APIConstants;
import com.supersit.GZFDA.db.LoadDBData;
import com.supersit.GZFDA.entity.UpdateInfo;
import com.supersit.GZFDA.util.AppManager;
import com.supersit.GZFDA.util.AppUtils;
import com.supersit.GZFDA.util.ButtonOnclickUtils;
import com.supersit.GZFDA.util.NetUtils;
import com.zhy.autolayout.AutoLayoutActivity;

public class LoginActivity extends AutoLayoutActivity {

	private EditText userName, password;
	private CheckBox auto_login;
	private Button btn_login;
	private String userNameValue, passwordValue;
	private SharedPreferences sp;
	private Context context;
	private ProgressDialog pd;
	// 当前版本号
	private String localVersion;
	// 服务器的版本信息
	private UpdateInfo updateInfo;

	@SuppressLint("WorldReadableFiles")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);
		AppManager.getAppManager().addActivity(LoginActivity.this);
		context = this;
		sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
		userName = (EditText) findViewById(R.id.et_zh);
		password = (EditText) findViewById(R.id.et_mima);
		// rem_pw = (CheckBox) findViewById(R.id.cb_mima);
		auto_login = (CheckBox) findViewById(R.id.cb_auto);
		btn_login = (Button) findViewById(R.id.btn_login);
		// btnQuit = (ImageButton)findViewById(R.id.img_btn);
		SQLiteDatabase db = LoadDBData.openDatabase(getApplicationContext());
		db.close();
		userNameValue = sp.getString("USER_NAME", "");
		passwordValue = sp.getString("PASSWORD", "");
		userName.setText(userNameValue);
		password.setText(passwordValue);
		if (sp.getBoolean("AUTO_ISCHECK", false)) {
			userNameValue = userName.getText().toString();
			passwordValue = password.getText().toString();
			login(userNameValue, passwordValue);
		}

		btn_login.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				// if (ButtonOnclickUtils.isFastClick()) {
				userNameValue = userName.getText().toString();
				passwordValue = password.getText().toString();
				if (TextUtils.isEmpty(userNameValue)
						&& TextUtils.isEmpty(passwordValue)) {
					Toast.makeText(context, "用户名或者密码不能为空", Toast.LENGTH_SHORT)
							.show();
				} else {
					login(userNameValue, passwordValue);
				}

				// }
			}
		});

		auto_login.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (auto_login.isChecked()) {
					System.out.println("自动登陆选中");
					sp.edit().putBoolean("AUTO_ISCHECK", true).commit();

				} else {
					System.out.println("自动登陆取消");
					sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
				}
			}
		});
	}

	private void login(final String username, final String password) {
		if (NetUtils.isConnected(context)) {
			pd = ProgressDialog.show(context, "登陆", "正在登陆，请稍后……");
			String url = APIConstants.login_api;
			RequestParams params = new RequestParams();
			params.put("account", username);
			params.put("password", password);
			Log.d("tag", "URL＝" + APIConstants.login_api + "account="
					+ username + "&password=" + password + "");
			AsyncHttpClient client = new AsyncHttpClient();
			client.setTimeout(1000 * 30);
			client.post(url, params, new AsyncHttpResponseHandler() {

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					super.onFailure(arg0, arg1, arg2, arg3);
					pd.dismiss();
					if (0 == arg0) {
						Toast.makeText(context, "登陆超时，请重新登陆!",
								Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(context, "服务器异常!", Toast.LENGTH_LONG)
								.show();
					}

				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub
					super.onSuccess(arg0, arg1, arg2);
					if (arg0 == 200) {
						String result = new String(arg2);
						pd.dismiss();
						Log.d("tag", "Login Success" + new String(arg2));
						JSONObject json_result = null;
						try {
							json_result = new JSONObject(result);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							// btn_login.setEnabled(true);
							Toast.makeText(context, "服务器异常", 0).show();
							e.printStackTrace();
						}
						if ("0".equals(json_result.opt("flag"))) {
							pd.dismiss();
							Toast.makeText(context, "登陆成功", Toast.LENGTH_SHORT)
									.show();
							Editor editor = sp.edit();
							editor.putString("USER_NAME", username);
							editor.putString("PASSWORD", password);
							editor.commit();
							Intent intent = new Intent(context,
									AddressSearch.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(intent);
							AppManager.getAppManager().finishActivity(
									LoginActivity.this);
						} else if ("1".equals(json_result.opt("flag"))) {
							// btn_login.setEnabled(true);
							Toast.makeText(context, "用户名或者密码错误，请检查",
									Toast.LENGTH_SHORT).show();
						}

					} else {
						Toast.makeText(context, "网络连接超时！", Toast.LENGTH_SHORT)
								.show();
					}
				}

			});
		} else {
			Toast.makeText(context, "网络异常，请检查网络连接！", Toast.LENGTH_SHORT).show();
			// NetUtils.openSetting(this);
		}
	}
}